package com.audaque.cloud.iqs.utils;

import com.audaque.cloud.iqs.ZkHiveBean;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

@Slf4j
public class HiveJdbcUtils {

    @SuppressFBWarnings("RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE")
    public static Connection getHiveConnection(ZkHiveBean zkHiveBean, String hiveEngine) throws Exception {
        // 默认7个小时
        Integer maxEvictableIdleTimeMillis = (1000 * 60 * 60 * 7);
        Integer socketTimeout = maxEvictableIdleTimeMillis / 1000;
        Class.forName(zkHiveBean.getDriverClass());
        DriverManager.setLoginTimeout(socketTimeout);
        Connection connection = DriverManager.getConnection(zkHiveBean.getUrl());
        System.setProperty("hive.execution.engine.switch", "true");
        System.setProperty("hive.execution.engine", hiveEngine==null?"spark":hiveEngine);
        log.info("tst:hiveEngine:"+hiveEngine);
        String engine = System.getProperty("hive.execution.engine", "spark");
        try(Statement statement = connection.createStatement()){
            statement.execute("set hive.execution.engine="+engine);
            log.info("execute set hive.execution.engine="+engine);
        }
        return connection;
    }
}
